﻿package co.th.bjc.md.online.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import co.th.bjc.md.dbonline.bean.BrandDBOnlineBean;
import co.th.bjc.md.dbonline.bean.CategoryDBOnlineBean;
import co.th.bjc.md.dbonline.bean.CustomerDBOnlineBean;
import co.th.bjc.md.dbonline.bean.CustomerDataDBOnlineBean;
import co.th.bjc.md.dbonline.bean.DepartmentDBOnlineBean;
import co.th.bjc.md.dbonline.bean.HospitalDBOnlineBean;
import co.th.bjc.md.dbonline.bean.HospitalDepartmentDBOnlineBean;
import co.th.bjc.md.dbonline.bean.ModelDBOnlineBean;
import co.th.bjc.md.dbonline.bean.ProductDBOnlineBean;
import co.th.bjc.md.dbonline.control.BrandDBOnlineControl;
import co.th.bjc.md.dbonline.control.CategoryDBOnlineControl;
import co.th.bjc.md.dbonline.control.CustomerDBOnlineControl;
import co.th.bjc.md.dbonline.control.DepartmentDBOnlineControl;
import co.th.bjc.md.dbonline.control.HospitalDBOnlineControl;
import co.th.bjc.md.dbonline.control.HospitalDepartmentDBOnlineControl;
import co.th.bjc.md.dbonline.control.ProductDBOnlineControl;

import net.sf.json.JSONArray;

public class CustomerDataManageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public CustomerDataManageServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html; charset=UTF-8");
		JSONArray jsonObject = new JSONArray();
		boolean status = false;
		String action = request.getParameter("action")==null?"":request.getParameter("action");
		
		if(action.equals("SEARCH")){
			PrintWriter out = response.getWriter();
			jsonObject = this.getSearchResult(request, response);
			out.print(jsonObject);
			
		}else if(action.equals("DELETE")){
			if(this.delete(request, response)){
				PrintWriter out = response.getWriter();
				status = true;
				jsonObject = this.getSearchResult(request, response);
				jsonObject.add(status);
				out.print(jsonObject);
			}
			
		}else if(action.equals("GETEDIT")){
			PrintWriter out = response.getWriter();
			jsonObject = getEditItem(request, response);
			status = true;
			jsonObject.add(status);
			out.print(jsonObject);
			
		}else if(action.equals("GETVIEW")){
			PrintWriter out = response.getWriter();
			jsonObject = getViewItem(request, response);
			status = true;
			jsonObject.add(status);
			out.print(jsonObject);
			
		}else if(action.equals("GETHOSPITAL")){
			PrintWriter out = response.getWriter();
			int regionId = Integer.parseInt(request.getParameter("id"));
			jsonObject = getHospitalList(regionId);
			out.print(jsonObject);
			
		}else if(action.equals("GETHOSPITALDEPARTMENT")){
			PrintWriter out = response.getWriter();
			int hospitalCode = Integer.parseInt(request.getParameter("id"));
			jsonObject = getHospitalDepartmentList(hospitalCode);
			out.print(jsonObject);
			
		}else if(action.equals("GETHOSPITALDEPARTMENTDETAIL")){
			PrintWriter out = response.getWriter();
			int hospitalCode = Integer.parseInt(request.getParameter("hospitalCode"));
			int departmentCode = Integer.parseInt(request.getParameter("departmentCode"));
			jsonObject = getHospitalDepartmentDetail(hospitalCode, departmentCode);
			out.print(jsonObject);
			
		}else if(action.equals("GETBJCDEPARTMENT")){
			PrintWriter out = response.getWriter();
			jsonObject = getBjcDepartment();
			out.print(jsonObject);
			
		}else if(action.equals("GETIMG")){
			getBlob(request, response);
			
		}else if(action.equals("GETRECORDS")){
			PrintWriter out = response.getWriter();
			jsonObject = getTotalRecord(request);
			out.print(jsonObject);
			
		}else if(action.equals("GETCATEGORY")){
			PrintWriter out = response.getWriter();
			jsonObject = getCategory();
			out.print(jsonObject);
			
		}else if(action.equals("GETBRAND")){
			PrintWriter out = response.getWriter();
			BigDecimal categoryCode = BigDecimal.valueOf(Long.parseLong(request.getParameter("categoryCode")));
			jsonObject = getBrand(categoryCode);
			out.print(jsonObject);
			
		}else if(action.equals("GETMODEL")){
			PrintWriter out = response.getWriter();
			BigDecimal category = BigDecimal.valueOf(Long.parseLong(request.getParameter("categoryCode")));
			BigDecimal brand = BigDecimal.valueOf(Long.parseLong(request.getParameter("brandCode")));
			jsonObject = getModel(category, brand);
			out.print(jsonObject);
			
		}else{
			getServletContext().getRequestDispatcher("/jsp/datamanage/manage_customerdata_main.jsp").forward(request, response);
			try{
				PrintWriter out = response.getWriter();
				List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
				for (FileItem item : items) {
		            if (item.isFormField()) {
		            	String fieldname = item.getFieldName();
		            	String fieldValue = item.getString();
		            	if(fieldname.equals("action")){
		            		if(fieldValue.equals("INSERT")){
		            			if(this.insert(items)){
		            				status = true;
		            				jsonObject = this.getSearchResult(request, response);
		            				jsonObject.add(status);
		            				out.print(jsonObject);
		            			}
		            		}
		            		break;
		            	}
		            }
		        }
			}catch(Exception ex){
				;
			}
		}
	}
	
	private JSONArray getSearchResult(HttpServletRequest request, HttpServletResponse response) {
		String type = request.getParameter("srh_type");
		String department = request.getParameter("srh_department");
		int minBed = chkNullToZero(request.getParameter("srh_bed_min"));
		int maxBed = chkNullToZero(request.getParameter("srh_bed_max"));
		int presidentImpRate = chkNullToZero(request.getParameter("srh_imp_rate_president"));
		int presidentRpRate = chkNullToZero(request.getParameter("srh_rp_rate_president"));
		int directorImpRate = chkNullToZero(request.getParameter("srh_imp_rate_director"));
		int directorRpRate = chkNullToZero(request.getParameter("srh_rp_rate_director"));
		int limitFrom = Integer.parseInt(request.getParameter("limitFrom"));
		int limitTo = Integer.parseInt(request.getParameter("limitTo"));
		
		
		CustomerDBOnlineBean bean = new CustomerDBOnlineBean();
		bean.setType(type);
		bean.setHospitalDepartment(department);
		bean.setBedCapacityMin(minBed);
		bean.setBedCapacityMax(maxBed);
		bean.setPresidentImpRate(presidentImpRate);
		bean.setPresidentRpRate(presidentRpRate);
		bean.setDirectorImpRate(directorImpRate);
		bean.setDirectorRpRate(directorRpRate);
		bean.setLimitFrom(BigDecimal.valueOf(limitFrom));
		bean.setLimitTo(BigDecimal.valueOf(limitTo));
		
		CustomerDBOnlineControl control = new CustomerDBOnlineControl();
		List<CustomerDBOnlineBean> list = control.searchCustomer(bean);
		JSONArray jsonObject = JSONArray.fromObject(list);
		return jsonObject;
	}
	
	private JSONArray getTotalRecord(HttpServletRequest request){
		JSONArray jsonObject = JSONArray.fromObject(null);
		return jsonObject;
	}
	
	private boolean insert(List<FileItem> items) {
//		CustomerData cus = new CustomerData();
		CustomerDataDBOnlineBean cus = new CustomerDataDBOnlineBean();
		
		boolean status = false;
		try{
			for (FileItem item : items) {
	            if (item.isFormField()) {
	                // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
	                String fieldname = item.getFieldName();
	                String fieldvalue = item.getString();
	                
	                if(fieldname.equals("ins_customerdata_code"))cus.setCustomerDataCode(fieldvalue);
	                else if(fieldname.equals("ins_region_name")) cus.setRegion(fieldvalue);
	                else if(fieldname.equals("ins_hospital_name_name_th")) cus.setHospitalNameTh(fieldvalue);
	                else if(fieldname.equals("ins_hospital_name_name_en")) cus.setHospitalNameEn(fieldvalue);
	                else if(fieldname.equals("ins_hospital_department_name")) cus.setHospitalDepartment(fieldvalue);
	                else if(fieldname.equals("ins_type")) cus.setType(fieldvalue);
	                else if(fieldname.equals("ins_bed_min")) cus.setBedCapacityMin(Integer.parseInt(fieldvalue));
	                else if(fieldname.equals("ins_bed_max")) cus.setBedCapacityMax(Integer.parseInt(fieldvalue));
	                else if(fieldname.equals("ins_hospital_address")) cus.setHospitalAddress(fieldvalue);
	                else if(fieldname.equals("ins_hospital_telephone")) cus.setHospitalTelephone(fieldvalue);
	                else if(fieldname.equals("ins_hospital_email")) cus.setHospitalEmail(fieldvalue);
	                else if(fieldname.equals("ins_president_name")) cus.setPresidentName(fieldvalue);
	                else if(fieldname.equals("ins_president_telephone")) cus.setPresidentTelephone(fieldvalue);
	                else if(fieldname.equals("ins_president_email")) cus.setPresidentEmail(fieldvalue);
	                else if(fieldname.equals("ins_imp_rate_president")) cus.setPresidentImpRate(Integer.parseInt(fieldvalue));
	                else if(fieldname.equals("ins_rp_rate_president")) cus.setPresidentRpRate(Integer.parseInt(fieldvalue));
	                else if(fieldname.equals("ins_director_name")) cus.setDirectorName(fieldvalue);
	                else if(fieldname.equals("ins_director_telephone")) cus.setDirectorTelephone(fieldvalue);
	                else if(fieldname.equals("ins_director_email")) cus.setDirectorEmail(fieldvalue);
	                else if(fieldname.equals("ins_imp_rate_director")) cus.setDirectorImpRate(Integer.parseInt(fieldvalue));
	                else if(fieldname.equals("ins_rp_rate_director")) cus.setDirectorRpRate(Integer.parseInt(fieldvalue));
	                else if(fieldname.equals("ins_remark1")) cus.setRemark1(fieldvalue);
	                else if(fieldname.equals("ins_bjc_department")) cus.setBjcDepartment(fieldvalue);
	                else if(fieldname.equals("ins_sale_person")) cus.setSalePerson(fieldvalue);
	                else if(fieldname.equals("ins_bjc_category")) cus.setBjcCategory(fieldvalue);
	                else if(fieldname.equals("ins_bjc_brand")) cus.setBjcBrand(fieldvalue);
	                else if(fieldname.equals("ins_bjc_model")) cus.setBjcModel(fieldvalue);
	                else if(fieldname.equals("ins_st_competitor")) cus.setStCompetitor(fieldvalue);
	                else if(fieldname.equals("ins_nd_competitor")) cus.setNdCompetitor(fieldvalue);
	                else if(fieldname.equals("ins_rd_competitor")) cus.setRdCompetitor(fieldvalue);
	                else if(fieldname.equals("ins_remark2")) cus.setRemark2(fieldvalue); 	
	                
	            } else {
	                // Process form file field (input type="file").
	                String filename = FilenameUtils.getName(item.getName());
	                if(!filename.equals("")){
						InputStream filecontent = item.getInputStream();
						cus.setImg(filecontent);
	                }
	            }
	        }
//			CustomerDBOnlineControl service = new CustomerDBOnlineControl();
//			status = service.
		}  catch (IOException e) {
			e.printStackTrace();
		} 
		return status;
	}
	
	private boolean update(HttpServletRequest request, HttpServletResponse response) {
		return false;
	}
	
	private boolean delete(HttpServletRequest request, HttpServletResponse response){
		return false;
	}
	
	private JSONArray getEditItem(HttpServletRequest request, HttpServletResponse response){
		BigInteger id = BigInteger.valueOf(Long.parseLong(request.getParameter("id")));
		CustomerDBOnlineBean bean = new CustomerDBOnlineControl().getViewItem(id);
		JSONArray json = JSONArray.fromObject(bean);
		return json;
	}
	
	private JSONArray getViewItem(HttpServletRequest request, HttpServletResponse response){
		BigInteger id = BigInteger.valueOf(Long.parseLong(request.getParameter("id")));
		CustomerDBOnlineControl control = new CustomerDBOnlineControl();
		CustomerDBOnlineBean bean = control.getViewItem(id);
		JSONArray json = JSONArray.fromObject(bean);
		return json;
	}
	
	private JSONArray getHospitalList(int regionId){
		List<HospitalDBOnlineBean> list = new HospitalDBOnlineControl().findHospitalByRegion(BigDecimal.valueOf(regionId));
		JSONArray json = JSONArray.fromObject(list);
		return json;
	}
	
	private JSONArray getHospitalDepartmentList(int hospitalCode){
		List<HospitalDepartmentDBOnlineBean> list = new HospitalDepartmentDBOnlineControl().findHospitalDepartmentByHospital(BigDecimal.valueOf(hospitalCode));
		JSONArray json = JSONArray.fromObject(list);
		return json;
	}
	
	private JSONArray getHospitalDepartmentDetail(int hospitalCode, int departmentCode){
		HospitalDepartmentDBOnlineBean obj = new HospitalDepartmentDBOnlineControl().findHospitalDepartmentByHospitalAndDepartment(BigDecimal.valueOf(hospitalCode), BigDecimal.valueOf(departmentCode));
		JSONArray json = JSONArray.fromObject(obj);
		return json;
	}
	
	private JSONArray getBjcDepartment(){
		List<DepartmentDBOnlineBean> list = new DepartmentDBOnlineControl().findAllDepartment();
		JSONArray json = JSONArray.fromObject(list);
		return json;
	}
	
	private void getBlob(HttpServletRequest request, HttpServletResponse response) throws IOException{
		String imageId = request.getParameter("imageId");
		InputStream in = null;//new CustomerDBOnlineControl().
		byte[] bytes = IOUtils.toByteArray(in);
		if(bytes.length > 0){
		    response.setContentType("image/jpeg");
		    OutputStream outputStream = response.getOutputStream();
		    outputStream.write(bytes);
		    outputStream.flush();
		    outputStream.close();
		}
	}
	
	private JSONArray getCategory(){
		List<CategoryDBOnlineBean> obj = new CategoryDBOnlineControl().findAllCategory();
		JSONArray json = JSONArray.fromObject(obj);
		return json;
	}
	
	private JSONArray getBrand(BigDecimal categoryCode){
		List<BrandDBOnlineBean> obj = new BrandDBOnlineControl().findBrandByCategory(categoryCode);
		JSONArray json = JSONArray.fromObject(obj);
		return json;
	}
	
	private JSONArray getModel(BigDecimal categoryCode, BigDecimal brandCode){
		List<ProductDBOnlineBean> obj = new ProductDBOnlineControl().findProductByCategoryAndBrand(categoryCode, brandCode);// new CustomerDBOnlineControl().getModel(brandCode);
		JSONArray json = JSONArray.fromObject(obj);
		return json;
	}
	
	private int chkNullToZero(Object obj){
		return obj == null || obj.equals("")?0:Integer.valueOf(obj.toString());
	}

}
